
class MockOption {
    enable: boolean = true
}

class Mock {
    mockData = []
    constructor() {
    }
    setConfig(config: MockOption): void {
        var _this = this;
        _this.mockData = []
        if (typeof config.enable === 'undefined' || !config.enable) return;
        const modules = import.meta.glob('@/mock/**/*', { eager: true })
        Object.keys(modules).forEach(key => {
            var v = modules[key].default;
            if (!v) return;
            if (Array.isArray(v)) {
                _this.mockData = _this.mockData.concat(v)
            } else {
                _this.mockData.push(v)
            }
        })
    }
    _findMockData(path) {
        for (var i = 0; i < this.mockData.length; i++) {
            var md = this.mockData[i];
            if (md.url === path) {
                if (typeof md.enable === 'undefined' || md.enable) return md.data;
            }
        }
        return false;
    }
    setAxios(axiosInstance): void {
        var _this = this;
        var srcAdapter = axiosInstance?.defaults?.adapter;
        axiosInstance.defaults.adapter = config => {
            var data = _this._findMockData(config.url);
            if (data) {
                return Promise.resolve({
                    status: 200,
                    statusText: 'OK',
                    _isAxiosMockFlag: true,
                    data: data
                })
            }
            return srcAdapter(config)
        }
    }
    isMockData(res): boolean {

        return res._isAxiosMockFlag != undefined
    }
    handleMockData(response): void {
        if (this.isMockData(response)) {
            response.config = {
                url: '',
                requestOptions: {
                    isReturnDefaultResponse: false,
                    isTransformResponse: true
                }
            }
            this.deleteMockFlag(response)
        }
    }
    afterMock(res): boolean {
        var find = this.isMockData(res)
        this.deleteMockFlag(res);
        return find
    }
    deleteMockFlag(res): void {
        if (res?._isAxiosMockFlag)
            delete res._isAxiosMockFlag;
    }
}



export default new Mock()




